// NotifyStatic.cpp : implementation file
//

#include "stdafx.h"
#include "manualCalib.h"
#include "NotifyStatic.h"
#include "cvvImage.h"
#include "cvxSf.h"


// CNotifyStatic

IMPLEMENT_DYNAMIC(CNotifyStatic, CStatic)

CNotifyStatic::CNotifyStatic()
: m_pData(NULL)
, m_image(NULL)
, m_pPts(NULL)
{
	m_isDrawPredict = false;
}

CNotifyStatic::~CNotifyStatic()
{
	if (m_image)
	{
		cvReleaseImage(&m_image);
	}
	if (m_pData)
	{
		delete m_pData, m_pData = NULL;
	}
}


BEGIN_MESSAGE_MAP(CNotifyStatic, CStatic)
	ON_WM_LBUTTONDOWN()
	ON_WM_PAINT()
END_MESSAGE_MAP()



// CNotifyStatic message handlers

void CNotifyStatic::addImage(IplImage *rgbImage, CvxBoard *board)
{
	ASSERT(rgbImage);
	ASSERT(board);

	if (m_image)
	{
		cvReleaseImage(&m_image);
	}
	if (m_pData)
	{
		delete m_pData, m_pData = NULL;
	}

	m_image = cvCloneImage(rgbImage);
	m_pData = new CCalibData();
	m_pData->addImage(m_image, board);
}


void CNotifyStatic::OnLButtonDown(UINT nFlags, CPoint point)
{
	// TODO: Add your message handler code here and/or call default
	CClientDC aDc(this);
	aDc.DPtoLP(&point);  //device coordinate to logic coordinate

	CRect r;
	GetClientRect(&r);
	double ratio = m_image->width/r.Width();

	//extract corners
	if(m_pData)
	{
		m_pData->addCorner(Point2f((float)point.x * ratio, (float)point.y * ratio));
		InvalidateRect(0, FALSE);
		//finish add corners
		if (m_pData->finishAddCorner())
		{
			int isOk = AfxMessageBox(_T("Accept Marked Corners ?"), MB_OKCANCEL);
			if (isOk == IDOK)
			{
				if (m_pPts)
				{
					bool isFound = m_pData->GetInsiderCorner(*m_pPts, true);			
					if (isFound)
					{
						m_isDrawPredict = true;					
					}
					else
					{
						AfxMessageBox(_T("Insider corner not found !"), MB_OK);
					}
				}
				else
				{
					AfxMessageBox(_T("Corner already found !"), MB_OK);
				}
				
			}
			else if (isOk == IDCANCEL)
			{
				m_pData->deleteAllCorners();
			}
			InvalidateRect(0, FALSE);
		}		
	}

	CStatic::OnLButtonDown(nFlags, point);
}

void CNotifyStatic::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	// TODO: Add your message handler code here
	// Do not call CStatic::OnPaint() for painting messages

	//draw image
	if (m_image)
	{
		CmfcImage leftImageDrawer;
		leftImageDrawer.passImage(m_image);	
		CRect rect;
		HDC hDc = dc.GetSafeHdc();
		GetClientRect(&rect);

		leftImageDrawer.DrawToHDC(hDc, &rect);

		if (m_pData && !m_isDrawPredict)
		{
			m_pData->Draw(&dc, 1.0 * rect.right /m_image->width);
		}
		else if (m_pData && m_isDrawPredict)
		{
			if (m_pPts)
			{
				m_pData->DrawPredictedPts(&dc, 1.0 * rect.right /m_image->width, *m_pPts);
			}
			
		}
		ReleaseDC(&dc);
	}	
}
